import 'package:decimal/decimal.dart';
import 'package:elegant_notification/elegant_notification.dart';
import 'package:elegant_notification/resources/arrays.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:stripe_connection_plugin/models/payment_intent.dart';
import 'package:stripe_connection_plugin/stripe_connection_plugin.dart';

import 'StripeController.dart';
import 'api.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  List? readers;
  String? token_flutter;
  String? token_android;

  final StripeController stripeController = Get.put(StripeController());
  Future<String> getConnectionString() async {
    // get api call using _dio to get connection token

    return "aaa";
  }
  @override
  void initState() {
    super.initState();

    // initPlatformState();
    // test() init();
  }



  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            Center(
              child: Text('Running on: $_platformVersion\n'),
            ),
            Center(
              child: Text('token_flutter:$token_flutter'),
            ),
            Center(
              child: Text('token_android:$token_android'),
            ),
            Center(
              child: ElevatedButton(onPressed: () async {
                // stripeController.sn.value = "STRM26142044270";
                await stripeController.stripeConnectionPlugin.permissionAllowed();
              },
                child: Text("permissionAllowed"),),
            ),
            Center(
              child: ElevatedButton(onPressed: () async {
                // stripeController.sn.value = "STRM26142044270";
                stripeController.sn.value = "STRM26142044270";
              },
                child: Text("init"),),
            ),
            Center(
              child: ElevatedButton(onPressed: () async {
                await Api().getToken().then((value) {
                  setState(() {
                    token_flutter = value;
                  });
                });
              },
                child: Text("request Token"),),
            ),
            Center(
              child: ElevatedButton(onPressed: () async {
                await stripeController.stripeConnectionPlugin.cashBox("zbox_F42D51842178");
              },
                child: Text("cashBox"),),
            ),
            Obx(() => Text(stripeController.cashBoxConnection.value?"连接":"断开")),
            Center(
              child: ElevatedButton(onPressed: () async {
                 stripeController.openCash();
              },
                child: Text("openCash"),),
            ),
            Center(
              child: ElevatedButton(onPressed: ()  {
               stripeController.cashBox.value="";
              },
                child: Text("initCashBox"),),
            ),
            Center(
              child: ElevatedButton(onPressed: ()  {
                stripeController.getCashBoxName();
              },
                child: Text("CashBoxgetZbox"),),
            ),
            Center(
              child: ElevatedButton(onPressed: () async {
                await stripeController.stripeConnectionPlugin.androidRequest().then((value){
                  setState(() {
                    token_android = value;
                  });
                });
              },
                child: Text("androidRequest"),),
            ),
            Center(
              child: ElevatedButton(onPressed: () async {
                print("_________");
              ElegantNotification.success(
                  width: 360,
                  notificationPosition: NotificationPosition.topLeft,
                  animation: AnimationType.fromTop,
                  title: Text('Update'),
                  description: Text('Your data has been updated'),
                  onDismiss: () {},
                ).show(context);
              },
                child: Text("ElegantNotification"),),
            ),
            Obx(() => Text(stripeController.log.value)),
            Obx(() => Text(stripeController.batteryLevel.value.toString())),
            Obx(() => Text(stripeController.connectionStatus.value)),
            Center(
              child: ElevatedButton(onPressed: () async{
                await Api()
                    .createPaymentIntent(Decimal.parse("10"))
                    .then((stripePayment) async => {


                  await stripeController.stripeConnectionPlugin
                      .retrievePaymentIntent(stripePayment['result']["clientSecret"])
                      .then((StripePaymentIntent
                  paymentIntent) async {

                    await stripeController.stripeConnectionPlugin
                        .processPayment()
                        .then((paymentsValue) {
                      print("@@@@@@@@@@@@@@@@@@@@@@@@@");
                      print(paymentsValue);
                      print(paymentsValue['status']);

                      if (paymentsValue['status'] ==
                          'REQUIRES_CAPTURE')
                        {
                          Api()
                              .capturePaymentIntent(
                              paymentsValue["id"],
                              stripePayment['result']["transferGroupId"])
                              .then((value) async {
                            print("_______________________________");
                          });
                        }

                    })
                        .catchError((e) {

                    });
                  }).timeout(const Duration(seconds: 30),onTimeout: (){
                    /**支付超过30秒自动取消订单意向 取消等待刷卡*/

                    stripeController.stripeConnectionPlugin
                        .cancelRetrievePaymentIntent();
                    stripeController.stripeConnectionPlugin
                        .cancelProcessPayment();

                  }).catchError((e) {
                    print("++++++++++++++++++++++++++++++++++++++++++");
                    print(e.toString());
                  }),

                });
              },
              child: Text("Create Order"),),
            )
          ],
        ),
      ),
    );
  }
}
